package com.vshop.controller.glkquery;

import com.alibaba.fastjson.JSON;
import com.vshop.entity.agatewaytobeijing.querydevice.beijing.response.DevicePackageOrder;
import com.vshop.entity.agatewaytobeijing.querydevice.beijing.response.QueryDeviceData;
import com.vshop.entity.agatewaytobeijing.querydevice.beijing.response.ResponseQueryDevice;
import com.vshop.entity.agatewaytobeijing.querypartnercode.response.ResponseQueryPartnerByDeviceId;
import com.vshop.entity.interfacerequest.useddata.response.ResponseUsedData;
import com.vshop.entity.interfacerequest.useddata.response.ResponseUsedDataTradeData;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.agatewaytobeijing.GatewayToBeijingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;

/**
 * 专门用于GLK-用deviceCode直接查询卡片的流量使用情况
 *
 * @author lm
 * @date 2019/07/16
 */
@RestController
@Api(value = "使用deviceCode查询流量使用")
@Slf4j
public class QueryUsedDataController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
    @Autowired
    PartnerInfoService partnerInfoService;
    /**
     * 请求网关的服务类
     */
    @Autowired
    GatewayToBeijingService toBeijingService;
    /**
     * 直接请求网关xml接口的地址
     */
    @Value("${iot.requestURI}")
    private String requestURI;

    @GetMapping("usedData/{deviceCode}")
    @CrossOrigin
    @ResponseBody
    @ApiOperation(value = "deviceCode查询流量使用", response = ResponseUsedData.class)

    public String query(@PathVariable(value = "deviceCode") String deviceCode) {

        //先判断链接中deviceCode有没有
        if (StringUtils.isBlank(deviceCode)) {
            //直接返回
            return responseStr("0010", "有効なICCID番号を入力してください", "0");
        }

        //1,先去北京的接口查询当前的渠道编码是多少 :用deviceCode去iot网关查询企业编码
        ResponseQueryPartnerByDeviceId response = toBeijingService.queryPartnerCode(deviceCode);

        //定义全局的返回内容
        ResponseUsedDataTradeData tra = null;

        if (null != response) {

            if (StringUtils.isNotBlank(response.getCode()) && Constant.RET_CODE_0000.equalsIgnoreCase(response.getCode()) && null != response.getData()) {

                if (StringUtils.isNotBlank(response.getData().getPartner_code())) {
                    String partnerCode = response.getData().getPartner_code();
                    String secret = partnerInfoService.getSecretByPartnerCode(partnerCode);
                    //根据deviceCode去接口查询当前设备
                    ResponseQueryDevice res = toBeijingService.queryDevice(deviceCode, partnerCode, secret);

                    if (null != res) {

                        if (StringUtils.isNotBlank(res.getCode()) && Constant.RET_CODE_0000.equalsIgnoreCase(res.getCode())) {

                            if (null != res.getData()) {

                                try {

                                    QueryDeviceData tr = res.getData();
                                    //0-库存期；1-静默期；2-使用期；3-停机保服务期；4-废弃回收期；5-内部库存期；
                                    String lifecycle = tr.getLifecycle();
                                    String lifecycleEndTime = tr.getLifecycle_end_time();

                                    if (StringUtils.isNotBlank(lifecycle)) {
                                        //静默期
                                        if (lifecycle.equals("1")) {
                                            //流量等参数值
                                            tra = new ResponseUsedDataTradeData();
                                            tra.setFlow("");
                                            tra.setSurplusFlow("");
                                            if (StringUtils.isNotBlank(lifecycleEndTime)) {
                                                tra.setExpireDate(sdf.format(new SimpleDateFormat("yyyymmdd").parse(lifecycleEndTime)));
                                            } else {
                                                tra.setExpireDate("");
                                            }
                                            //成功返回
                                            return responseSuccessStr(tra, "0000", "success", "1");
                                        }
                                        //使用期
                                        else if (lifecycle.equals("2")) {

                                            if (null != tr.getPackage_order()) {

                                                DevicePackageOrder order = tr.getPackage_order();
                                                String orderCode = order.getOrderCode();
                                                String flow = order.getFlow();
                                                String flowUseRate = order.getFlowUseRate();
                                                NumberFormat nf = NumberFormat.getPercentInstance();
                                                String rate = String.valueOf(nf.parse(flowUseRate));
                                                float scale = Float.valueOf(rate) * Float.valueOf(flow);
                                                String usedFlow = new DecimalFormat("##").format(scale);
                                                String surplusFlow = String.valueOf(Integer.valueOf(flow) - Integer.valueOf(usedFlow));
                                                String expireDate = order.getExpireDate();

                                                if (StringUtils.isNotBlank(orderCode) && StringUtils.isNotBlank(flow) && StringUtils.isNotBlank(surplusFlow)) {
                                                    //流量等参数值
                                                    tra = new ResponseUsedDataTradeData();
                                                    tra.setFlow(flow);
                                                    tra.setSurplusFlow(surplusFlow);
                                                    if (StringUtils.isNotBlank(expireDate)) {
                                                        tra.setExpireDate(sdf.format(new SimpleDateFormat("yyyymmdd").parse(expireDate)));
                                                    } else {
                                                        tra.setExpireDate("");
                                                    }

                                                    //成功返回
                                                    return responseSuccessStr(tra, "0000", "success", "1");

                                                } else {
                                                    //虽然有订单，但是参数都为空   //日程类套餐不支持流量查询!
                                                    return responseStr("0019", "有効なICCID番号を入力してください", "0");
                                                }


                                            } else {
                                                //虽然有正在使用的订单，但是奇怪订单为空
                                                return responseStr("0018", "有効なICCID番号を入力してください", "0");
                                            }

                                        } else {
                                            //其他状态不符合返回规则
                                            //设备不在静默和使用期内!
                                            return responseStr("0017", "有効なICCID番号を入力してください", "0");
                                        }

                                    } else {
                                        //设备所处生命周期为空 :旅游卡、MIFI为空
                                        return responseStr("0016", "有効なICCID番号を入力してください", "0");
                                    }


                                } catch (Exception e) {
                                    //遇到异常情况
                                    return responseStr("0015", "有効なICCID番号を入力してください", "0");
                                }
                            } else {
                                //虽然查询结果是0000成功，但是订单可能为空的
                                return responseStr("0014", "有効なICCID番号を入力してください", "0");
                            }

                        } else {
                            //查询订单有返回，但是不成成功
                            return responseStr(res.getCode(), "有効なICCID番号を入力してください!", "0");
                        }

                    } else {
                        //接口返回为空：
                        return responseStr("0013", "有効なICCID番号を入力してください", "0");
                    }


                } else {
                    //虽然有结果并且是0000，但是没有正确的信息返回，也只能直接返回无正确结果返回
                    return responseStr("0012", "有効なICCID番号を入力してください!", "0");
                }

            } else {
                //虽然有结果返回，但是结果不是0000，所以直接返回原因
                return responseStr(response.getCode(), "有効なICCID番号を入力してください", "0");
            }

        } else {
            //北京接口返回有误
            return responseStr("0011", "有効なICCID番号を入力してください", "0");
        }

    }


    /***
     * 异常规范返回
     * @param retCode
     * @param resultInfo
     * @return
     */
    private String responseStr(String retCode, String resultInfo, String status) {
        ResponseUsedData response = new ResponseUsedData();
        response.setRetCode(retCode);
        response.setRetMsg(resultInfo);
        response.setStatus(status);
        String jsonString = JSON.toJSONString(response);
        log.info("【用于GLK查询异常响应】：" + resultInfo + "结果：" + jsonString);
        return jsonString;
    }

    /***
     * 成功规范返回
     * @param tradeData
     * @param retCode
     * @param resultInfo
     * @return
     */
    private String responseSuccessStr(ResponseUsedDataTradeData tradeData, String retCode, String resultInfo, String status) {
        ResponseUsedData response = new ResponseUsedData();
        response.setTradeData(tradeData);
        response.setRetCode(retCode);
        response.setRetMsg(resultInfo);
        response.setStatus(status);
        String jsonString = JSON.toJSONString(response);
        log.info("【用于GLK查询成功响应】：" + resultInfo + "结果：" + jsonString);
        return jsonString;
    }

}
